<template>
  <van-nav-bar title="VueShop" />

  <van-tree-select v-model:main-active-index="active" height="100vh" :items="items" @click-nav="onTypeChange">
    <template #content>
      <!-- 下拉刷新 -->
    <van-pull-refresh v-model="refreshing" @refresh="refresh">
      <!-- 加载列表 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :offset="10"
        :immediate-check="false"
        finished-text="没有更多了"
        @load="load"
      >
        <van-card
        :price="product.price"
        :tag="product.flag_text"
        :title="product.name"
        :thumb="product.thumbs_text"
        v-for="product in list"
        :key="product.id"
      >
      <template #tags>
        <van-tag type="success" v-if="product.stock_status=='1'">库存充足</van-tag>
        <van-tag type="warning" v-else-if="product.stock_status=='2'">即将售罄</van-tag>
        <van-tag type="danger" v-else>已售罄</van-tag>
      </template>
        <template #num>
          <van-button size="mini" @click="ProductInfo(product.id)">查看详情</van-button>
        </template>
        </van-card>
      </van-list>
    </van-pull-refresh>

    <!-- 返回顶部 -->
    <van-back-top />
    </template>
  </van-tree-select>

  <Tabbar />
</template>

<script setup>

  const {proxy} = getCurrentInstance()

  let active = ref(0)
  let items = ref([])

  let list = ref([]) //数据列表
  let page = ref(1)  //分页
  let loading = ref(false) //加载状态
  let finished = ref(false) //是否无更多数据
  let refreshing = ref(false) //下拉刷新
//下拉刷新
  const refresh = async () =>
  {
    page.value = 1
    list.value = []
    finished.value = false
    loading.value = true

    load()
  }

  //加载数据方法
  const load = async () =>
  {
    let result = await proxy.$GET({
      url:'/product/index',
      params:{
        pageSize:6,
        page:page.value,
        type:items.value[active.value].id,
      }
    })
    if(result)
    {
      list.value = list.value.concat(result.data)
      refreshing.value = false
      loading.value = false
      finished.value = !result.has_more
      if(result.has_more)  page.value++
    }
  }

  onBeforeMount(async()=>{
    //初始化分类列表
    let result = await proxy.$GET({
      url:'/product/type'
    })
    result.forEach(e => {
      items.value.push({text: e.name, id: e.id})
    });
    load()
  })
  const onTypeChange = (index)=>{
    active.value = index
    refresh()
  }
  const ProductInfo = (pid) => proxy.$router.push(`/product/info?id=${pid}`)
</script>